import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_search_bar_widget/common_search_bar_widget.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/company_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail/widgets/company_detail_search_list_widget.dart';
import 'package:e_reception_flutter/ui/company/company_detail_by_type_list/company_detail_by_type_list_widget.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/bind_terminal_info_confirm_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/terminal_detail_info_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/terminal_pic_detail_page.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:flutter/material.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import '../../app_main.dart';
import '../set_terminal_status_menu_dialog.dart';
import 'bean/new_terminal_response_bean.dart';
import 'bean/set_terminal_state_type.dart';
import 'new_terminal_list_page.dart';
import 'new_terminal_list_view_model.dart';

/// 终端搜索页
class SearchTerminalListPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SearchTerminalListPage";
  final String gps;
  const SearchTerminalListPage({Key key,this.gps,}):super(key: key);
  @override
  _SearchTerminalListPageState createState() =>
      _SearchTerminalListPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context, String gps) {
    return RouterUtils.routeForFutureResult(
      context,
      SearchTerminalListPage(
        gps:gps,
      ),
      routeName: SearchTerminalListPage.ROUTER,
    );
  }
}

class _SearchTerminalListPageState extends BaseState<SearchTerminalListPage> {

  NewTerminalListViewModel _viewModel;
  String _gps;
  String _searchStr;
  @override
  void initState() {
    super.initState();
    _gps = widget?.gps??"";
    _viewModel = NewTerminalListViewModel(this, allflg: "01", gps: _gps);
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // backgroundColor: Color(0xFF22263a),
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: Column(
        children: <Widget>[
          SizedBox(
            height: ScreenUtils.getStatusBarH(context),
          ),
          _toSearchBarWidget(),
          Expanded(
            child: _toPlaceHolderWidget(),
          )
        ],
      ),
    );
  }

  Widget _toSearchBarWidget() {
    return Container(
      height: 44,
      child: Row(
        children: <Widget>[
          Expanded(
            child: CommonSearchBarWidget(
                hintText: "输入备注/机身编码/设备ID",
                autoFocus: true,
                margin: const EdgeInsets.only(left: 15),
                onChanged: (String searchStr) {
                  _searchStr = searchStr?.trim();
                  _viewModel.searchTerminal(context, _searchStr);
                },
                onSubmitted: (String searchStr) {
                  _searchStr = searchStr?.trim();
                  _viewModel.searchTerminal(context, _searchStr);
                }),
          ),
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              RouterUtils.pop(context);
            },
            child: Container(
              width: 60,
              height: 30,
              child: Center(
                child: Text(
                  "取消",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: Color(0xFFD0E0F7), fontSize: 15, height: 1.2),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _toPlaceHolderWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.statusTypeValueNotifier,
        builder:
            (BuildContext context, PlaceHolderStatusType value, Widget child) {
          return VgPlaceHolderStatusWidget(
            loadingStatus: false,
            errorStatus: value == PlaceHolderStatusType.error,
            emptyStatus: value == PlaceHolderStatusType.empty,
            errorOnClick: () => _viewModel
                .searchTerminal(context, _searchStr),
            loadingOnClick: () => _viewModel
                .searchTerminal(context, _searchStr),
            child: child,
          );
        },
        child: _toBodyWidget());
  }

  Widget _toBodyWidget() {
    return ValueListenableBuilder(
        valueListenable: _viewModel?.terminalSearchValueNotifier,
        builder: (BuildContext context, List<NewTerminalListItemBean> data, Widget child){
          return ListView.separated(
              itemCount: data?.length ?? 0,
              padding: const EdgeInsets.all(0),
              physics: BouncingScrollPhysics(),
              keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
              itemBuilder: (BuildContext context, int index) {
                return _toListItemWidget(context, index, data?.elementAt(index), data?.length);
              },
              separatorBuilder: (BuildContext context, int index) {
                return SizedBox(height: 0);
              });
        }
    );
  }

  ///列表项
  Widget _toListItemWidget(BuildContext context, int index,
      NewTerminalListItemBean itemBean, int count) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () async {
        if (StringUtils.isEmpty(itemBean?.hsn)) {
          VgToastUtils.toast(AppMain.context, "终端获取异常");
          return;
        }
        dynamic result = await TerminalDetailInfoPage.navigatorPush(
            context, itemBean?.hsn, terminalCount: count ?? 0,
            router: NewTerminalListPage.ROUTER);
        if (result is bool && result) {
          _viewModel?.refresh();
        }
      },
      child: Container(
        height: 102,
        child: Row(
          children: <Widget>[
            SizedBox(
              width: 15,
            ),
            ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Container(
                  width: 78,
                  height: 78,
                  color: Color(0xFF191E31),
                  child: VgCacheNetWorkImage(
                    itemBean?.terminalPicurl ?? "",
                    defaultErrorType: ImageErrorType.head,
                    errorWidget: Container(
                      child: Image.asset(
                        "images/icon_terminal_holder.png",
                        fit: BoxFit.cover,
                      ),
                    ),
                    placeWidget: Container(
                      child: Image.asset(
                        "images/termial_empty_place_holder_ico.png",
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                )),
            Expanded(child: _toContentWidget(context, index, itemBean)),
            _toButtonStatusWidget(itemBean),
          ],
        ),
      ),
    );
  }

  Widget _toContentWidget(context, int index, NewTerminalListItemBean itemBean) {
    SetTerminalStateType currentType = itemBean.getTerminalState();
    return Container(
      margin: const EdgeInsets.only(left: 12),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: <Widget>[
              Visibility(
                visible: (StringUtils.isEmpty(itemBean?.terminalName) && StringUtils.isEmpty(itemBean?.sideNumber)&& StringUtils.isNotEmpty(itemBean?.hsn)),
                child: Text(
                  // "硬件ID：",
                  "",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    // fontWeight: FontWeight.w600
                  ),
                ),
              ),
              Expanded(
                child: Text(
                  itemBean?.getTerminalName(index),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    // fontWeight: FontWeight.w600
                  ),
                ),
              ),
              GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTapUp: (detail){
                  if(itemBean?.getTerminalIsOff()??true){
                    return;
                  }
                  SetTerminalStatusMenuDialog.navigatorPushDialog(context,
                        (currentState){
                      _onOpen?.call(currentState, itemBean?.hsn);
                    },
                        (currentState){
                      _screenOff?.call(currentState, itemBean?.hsn);
                    },
                        (currentState){
                      _off?.call(currentState, itemBean?.hsn);
                    },
                        (time){

                    },
                    itemBean?.getTerminalState(),
                    itemBean?.autoOnoffTime??"",
                    itemBean?.autoOnoffWeek??"",
                    itemBean.hsn,
                    itemBean.id,
                    itemBean?.getTerminalName(index),
                    itemBean?.autoOnoff,
                    itemBean?.comAutoSwitch,
                  );
                  // TerminalStateMenuDialogUtils.showMenuDialog(
                  //     context: context,
                  //     tabUpDetails: detail,
                  //     itemMap: _getMenuMap(context, itemBean),
                  //     sortType: currentType
                  // );
                },
                child: Container(
                  alignment: Alignment.centerRight,
                  padding: EdgeInsets.symmetric(horizontal: 15),
                  child: Row(
                    children: [
                      // SizedBox(width: 20,),
                      Container(
                        alignment: Alignment.centerRight,
                        // width: 80,
                        padding: EdgeInsets.symmetric(vertical: 2.5),
                        child: Text(
                          itemBean.getTerminalStateString(),
                          style: TextStyle(
                            fontSize: 12,
                            color: (itemBean?.getTerminalIsOff()??true)
                                ?ThemeRepository.getInstance().getDefaultGrayColor_FF5E687C()
                                :ThemeRepository.getInstance().getHintGreenColor_00C6C4(),
                          ),
                        ),
                      ),
                      Visibility(
                        visible: !(itemBean?.getTerminalIsOff()??true),
                        child: Row(
                          children: [
                            SizedBox(width: 5,),
                            Image(
                              image: AssetImage("images/icon_shape_arrow_down.png"),
                              width: 7,
                            ),
                          ],
                        ),
                      ),

                    ],
                  ),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 2,
          ),
          Container(
            margin: const EdgeInsets.only(right: 12),
            child: Text(
              showOriginEmptyStr(itemBean?.position) ?? itemBean?.address ?? "",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                color: VgColors.INPUT_BG_COLOR,
                fontSize: 12,
              ),
            ),
          ),
          SizedBox(
            height: 2,
          ),
          Text(
            "管理员：${itemBean?.manager ?? "-"}${_getLoginStr(itemBean?.loginName) ?? ""}",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 12,
            ),
          ),
          SizedBox(
            height: 3,
          ),
          _toAccountStatus(itemBean),
        ],
      ),
    );
  }

  String _getLoginStr(String loginName) {
    if (loginName == null || loginName == "") {
      return null;
    }
    return "（$loginName账号登录）";
  }

  Widget _toAccountStatus(NewTerminalListItemBean itemBean){
    return Row(
      children: [
        Text(
          "账号状态：",
          style: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 12,
              height: 1.22
          ),
        ),
        Text(
          itemBean.getEndDayString(),
          style: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 12,
              height: 1.2
          ),
        ),
        Text(
          itemBean.getNotifyString(),
          style: TextStyle(
              color: ThemeRepository.getInstance().getMinorRedColor_F95355(),
              fontSize: 12,
              height: 1.2
          ),
        ),
        // Container(
        //   width: 63,
        //   alignment: Alignment.center,
        //   child: Text(
        //     "（10天后）",
        //     maxLines: 1,
        //     overflow: TextOverflow.ellipsis,
        //     style: TextStyle(
        //       color: ThemeRepository.getInstance().getMinorRedColor_F95355(),
        //       fontSize: 12,
        //     ),
        //   ),
        // )
      ],
    );
  }
  void _onOpen(SetTerminalStateType currentState, String hsn){
    print("开机");
    _viewModel.terminalOffScreen(context, hsn, "00", callback: (){
    });
  }

  void _screenOff(SetTerminalStateType currentState, String hsn){
    print("息屏开机");
    _viewModel.terminalOffScreen(context, hsn, "01", callback: (){
    });
  }

  void _off(SetTerminalStateType currentState, String hsn){
    print("关机");
    _viewModel.terminalOff(context, hsn, callback: (){
    });
  }

  Widget _toButtonStatusWidget(NewTerminalListItemBean itemBean) {
    if (!(itemBean?.bindflg == "00")) {
      // return SizedBox(
      //   width: 15,
      // );
    }
    return Offstage(
      offstage: !(itemBean?.bindflg == "00"),
      child: Container(
        width: 90,
        child: _toBindButtonWidget(itemBean),
      ),
    );
  }

  Widget _toBindButtonWidget(NewTerminalListItemBean itemBean) {
    return Align(
      alignment: Alignment.topCenter,
      child: Builder(
        builder: (BuildContext context) => Container(
          width: 60,
          height: 28,
          margin: const EdgeInsets.symmetric(vertical: 12),
          decoration: BoxDecoration(
              color: ThemeRepository.getInstance().getMinorRedColor_F95355(),
              borderRadius: BorderRadius.circular(14)),
          child: Center(
            child: Text(
              "绑定",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(color: Colors.white, fontSize: 13, height: 1.2),
            ),
          ),
        ),
      ),
    );
  }
}
